package com.bm.service.Impl;


import com.bm.enums.OrderStatus;
import com.bm.exception.DirSirException;
import com.bm.exception.ExceptionCode;
import com.bm.model.Commodity;
import com.bm.model.DeliveryTeam;
import com.bm.model.Order;
import com.bm.service.IOrderService;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.bm.enums.OrderStatus.*;
import static com.bm.util.Goods.getAllGoods;

public class OrderService implements IOrderService {
    List<Commodity> allGoods = getAllGoods();

    @Override
    public Order userOrder(Order order) {
        //校验商品
        for (Commodity ag : allGoods) {
            if (Objects.equals(order.getId(), ag.getId()) && order.getQuantity() > ag.getCount()) {
                throw new DirSirException(ExceptionCode.INSUFFICIENT_STOCK);
            }
        }
        //生成订单
        order.setStatus(UNPAID);
        //订单号
        System.out.println(getOrderNumber());

        return order;
    }

    //创建订单号
    private static long getOrderNumber() {
        LocalDate currentDate = LocalDate.now(); // 获取当前日期
        int year = currentDate.getYear(); // 获取年份
        int month = currentDate.getMonthValue(); // 获取月份（1-12）
        int day = currentDate.getDayOfMonth(); // 获取日期
        System.out.println("当前日期：" + year + "-" + month + "-" + day);
        int code = (int) (Math.random() * 900000) + 100000;
        System.out.println(code);
        return year + month + day + code;
    }

    LocalDateTime localDateTime = LocalDateTime.now();

    @Override
    public boolean paymentSuccess() {
        List<DeliveryTeam> teams = new ArrayList<>();
        Order order = new Order();
        DeliveryTeam deliveryTeam = new DeliveryTeam();
        if (order.getStatus() == PAID) {
            //更新订单状态
            order.setStatus(PENDING_SHIPMENT);
            System.out.println(localDateTime);
            //生成发货任务:将订单信息写入 发货队列表（字段：订单号、数量、收货地址）
            deliveryTeam.setOrderNumber(getOrderNumber());
            deliveryTeam.setQuantity(order.getQuantity());
            deliveryTeam.setAddress(order.getAddress());
            teams.add(deliveryTeam);
            return true;
        }
        return false;
    }

    @Override
    public void whProcessing(Order order) {

        for (Commodity ag : allGoods) {
            //场景1：库存充足
            if (order.getQuantity() < ag.getCount()) {
                //人工分配物流：
                String ad = order.getAddress();
                System.out.println("韵达");
                //打印面单：
                System.out.println("发货时间：，发货快递：韵达"+localDateTime);
                order.setStatus(SHIPPED);
            }
            //场景2：库存不足
            if (order.getQuantity() > ag.getCount()){
                order.setStatus(SOLD_OUT);
                System.out.println("商品缺货，预计3天内补发");
            }
        }


    }
}
